
import chatStore from '../store/chat';
import { InitChatInfo, InitSender } from '../type/chat';
import { userData, userInfoByBack } from '../type/user';
import { getTime } from '../utils/dateTime';
import { getUserInfo } from './user/user';
let lockReconnect=false;
export const createSocket=()=>{
	try{
		 init();
	}catch(e){
		reconnect();
	}
}
const init=()=>{
	let user: userData = uni.getStorageSync('userInfo');
	if(user){
	 let socketTask= uni.connectSocket({
	 url: 'ws://localhost:2212/back/chat/' + user.pkId,
	 success: () => {
	 	console.log('连接建立成功');
	 }
	 });	
	socketTask.onOpen((res:any) => {
		console.log('连接成功了哟');
		//开启心跳检测
		heartCheck.start();
	});
	//使用本地缓存 1.保存接收消息 2.未读消息的计数
	//聊天页面和此方法 同时接收消息 聊天页面用于同时 获取消息 此方法作为 接收未读消息  聊天页面关闭后会覆盖掉未读消息 不必担心消息数组缓存存在问题
	socketTask.onMessage((res: any) => {
		if('HeartBeat'===res.data){
			return;
		}
		let data = JSON.parse(res.data);
		let fromMsgId: string = data.from;
		console.log(data);
	    //判定聊天列表是否存在该发送用户 未存在 需添加
		if (!chatStore.isExistSender(fromMsgId)) {
			getUserInfo(fromMsgId).then((data: userInfoByBack) => {
				let chatter=new InitSender();
				chatter.senderId=data.pkId;
				chatter.senderImg=data.userImg;
				chatter.senderName=data.username;
				chatStore.addSender(chatter);
			});
		}
		let chatSeller = new InitChatInfo();
		chatSeller.sendUser = 1;
		chatSeller.sendMessage = data.text;
		let list: Array<InitChatInfo> = [...uni.getStorageSync(fromMsgId)];
		list.push(chatSeller);
		uni.setStorageSync(fromMsgId, list);
		let unreadNum: number = uni.getStorageSync('unRead' + fromMsgId);
		unreadNum++;
		uni.setStorageSync('unRead' + fromMsgId, unreadNum);
		let sendTime: string = getTime();
		console.log(sendTime);
		uni.setStorageSync('sendTime' + fromMsgId, sendTime);
		//收到消息 重置心跳检测
		heartCheck.start();
	}
	);
	socketTask.onError(()=>{
		reconnect();
	});
}
}


export function sendMessage(message: string) {
	    uni.sendSocketMessage({
	      data: message
	    });
}
//异常或者被关闭后隔时间重连
export const reconnect=()=>{
	if(lockReconnect) return;
	lockReconnect=true;
	setTimeout(()=>{
		createSocket();
		lockReconnect=false;
	},1000*60*1)
}
//重连代码时序：当服务端Down掉或网络断开超过一定时间serverTimeoutObj这个延迟器会执行，然后调用socketTask.close()关闭连接并且触发onClose事件，
//在onClose事件中会调用reconnect方法，而reconnect又会调用createWebSocket方法，createWebSocket去创建WebSocket连接，当创建异常时又会再调用reconnect，一直到能连接得上。
let heartCheck={
	timeout:1000*50,
	serverTimeout:1000*55,
	sendtimeoutObj:null,
	serverTimeoutObj:null,
    start:function(){
		let that=this;
		this.sendtimeoutObj && clearTimeout(this.sendtimeoutObj);
		this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
		this.sendtimeoutObj=setTimeout(function(){
			sendMessage("HeartBeat");
			that.serverTimeoutObj=setTimeout(function(){
				uni.onSocketClose(function () {
				  console.log('WebSocket 已关闭！');
				  reconnect();
				});
			},that.serverTimeout);
		},this.timeout);
	}
}

